﻿using System;
using System.IO;
using System.Web;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
namespace GBlog.Core.Recaptcha
{
    public class RecaptchaValidator
    {
        private const string VerifyUrl = "http://www.google.com/recaptcha/api/verify";
        private string privateKey;
        private string remoteIp;
        private string challenge;
        private string response;
        private IWebProxy proxy;
        public string PrivateKey
        {
            get
            {
                return this.privateKey;
            }
            set
            {
                this.privateKey = value;
            }
        }
        public string RemoteIP
        {
            get
            {
                return this.remoteIp;
            }
            set
            {
                IPAddress ıPAddress = IPAddress.Parse(value);
                if (ıPAddress == null || (ıPAddress.AddressFamily != AddressFamily.InterNetwork && ıPAddress.AddressFamily != AddressFamily.InterNetworkV6))
                {
                    throw new ArgumentException("Expecting an IP address, got " + ıPAddress);
                }
                this.remoteIp = ıPAddress.ToString();
            }
        }
        public string Challenge
        {
            get
            {
                return this.challenge;
            }
            set
            {
                this.challenge = value;
            }
        }
        public string Response
        {
            get
            {
                return this.response;
            }
            set
            {
                this.response = value;
            }
        }
        public IWebProxy Proxy
        {
            get
            {
                return this.proxy;
            }
            set
            {
                this.proxy = value;
            }
        }
        private void CheckNotNull(object obj, string name)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(name);
            }
        }
        public RecaptchaResponse Validate()
        {
            this.CheckNotNull(this.PrivateKey, "PrivateKey");
            this.CheckNotNull(this.RemoteIP, "RemoteIp");
            this.CheckNotNull(this.Challenge, "Challenge");
            this.CheckNotNull(this.Response, "Response");
            RecaptchaResponse result;
            if (!(this.challenge == string.Empty) && !(this.response == string.Empty))
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com/recaptcha/api/verify");
                httpWebRequest.ProtocolVersion = HttpVersion.Version10;
                httpWebRequest.Timeout = 30000;
                httpWebRequest.Method = "POST";
                httpWebRequest.UserAgent = "reCAPTCHA/ASP.NET";
                if (this.proxy != null)
                {
                    httpWebRequest.Proxy = this.proxy;
                }
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                string s = string.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", new object[]
				{
					HttpUtility.UrlEncode(this.PrivateKey),
					HttpUtility.UrlEncode(this.RemoteIP),
					HttpUtility.UrlEncode(this.Challenge),
					HttpUtility.UrlEncode(this.Response)
				});
                byte[] bytes = Encoding.ASCII.GetBytes(s);
                using (Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
                string[] array;
                try
                {
                    using (WebResponse webResponse = httpWebRequest.GetResponse())
                    {
                        using (TextReader textReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                        {
                            array = textReader.ReadToEnd().Split(new string[]
							{
								"\n",
								"\\n"
							}, StringSplitOptions.RemoveEmptyEntries);
                        }
                    }
                }
                catch (WebException ex)
                {
                    EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
                    result = RecaptchaResponse.RecaptchaNotReachable;
                    return result;
                }
                string text = array[0];
                if (text != null)
                {
                    if (text == "true")
                    {
                        result = RecaptchaResponse.Valid;
                        return result;
                    }
                    if (text == "false")
                    {
                        result = new RecaptchaResponse(false, array[1].Trim(new char[]
						{
							'\''
						}));
                        return result;
                    }
                }
                throw new InvalidProgramException("Unknown status response.");
            }
            result = RecaptchaResponse.InvalidSolution;
            return result;
        }
    }
}